<template>
  <div class="page-login">
    <div class="page-login-header">
      <div class="title">
        <div class="logo"></div>
        <div class="app-name">{{$appName}}</div>
      </div>
      <div class="toolbar">
        <div class="help" @click="toolsBarModelOpen('help')"></div>
      </div>
    </div>
    <div class="login-layer">
      <el-tabs v-model="loginActiveName" v-show="accountLoginTabShow">
        <el-tab-pane label="账号登录" name="accountLogin">
          <el-form
            ref="loginForm"
            label-position="top"
            :rules="accountLoginFormRules"
            :model="formLogin"
            size="default">
            <el-form-item class="login-form-item" prop="username">
              <el-input placeholder="请输入账号" prefix-icon="el-icon-user" v-model="formLogin.username"> </el-input>
            </el-form-item>
            <el-form-item class="login-form-item" prop="password">
              <el-input
                placeholder="请输入密码"
                type="password"
                show-password
                prefix-icon="el-icon-lock"
                v-model="formLogin.password">
              </el-input>
            </el-form-item>
            <!-- 滑块验证码 -->
            <div class="login-form-item slide">
              <el-form-item prop="verify">
                <dd-slider ref="verify" 
                          :width="verifyWidth" 
                          :height="verifyHeight"
                          :borderRadius="5"
                          :blockWidth="45"
                          borderColor="#eee"
                          bgColor="#F2F4F4"
                          @success="successVerify">
                </dd-slider>
              </el-form-item>
            </div>
          </el-form>

          <div class="login-form-item">
            <div class="forget" @click="switchModel('modifiedPassword')"><span>忘记密码 ？</span></div>
          </div>
          <div class="login-form-item">
            <el-button type="primary" @click="loginSubmit" :loading="loading">登 录</el-button>
          </div>
          <div class="no-account">
            <span>没有账号？ <span class="register" @click="switchModel('accountRegister')">注册新账号</span></span>
          </div>
        </el-tab-pane>
        <el-tab-pane label="手机登录" name="phoneLogin">
          <el-form
            ref="cellphoneLoginForm"
            label-position="top"
            :rules="cellphoneLoginFormRules"
            :model="cellphoneLoginForm"
            size="default">
            <el-form-item class="login-form-item" prop="cellphone">
              <el-input
                placeholder="请输入您的手机号码"
                prefix-icon="el-icon-phone-outline"
                v-model="cellphoneLoginForm.cellphone">
              </el-input>
            </el-form-item>
            <el-form-item class="login-form-item" prop="verifyCode">
              <el-row :gutter="14">
                <el-col :span="14">
                  <el-input
                    placeholder="请输入验证码"
                    prefix-icon="el-icon-chat-dot-square"
                    v-model="cellphoneLoginForm.verifyCode">
                  </el-input>
                </el-col>
                <el-col :span="10">
                  <div class="send-verify">
                    <el-button plain @click="sendCellphoneLoginVerify()" :disabled="this.cellphoneLoginVerifySending">{{
                      this.cellphoneLoginVerifySending ? `${this.cellphoneLoginVerifyCountDown}s` : '发送验证码'
                    }}</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>

          <div class="login-form-item">
            <el-button type="primary" @click="cellphoneLoginSubmit" :loading="loading">登 录</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div v-show="modifyPwdTabShow">
        <div class="back-login" @click="switchModel('accountLogin')">
          <i class="el-icon-caret-left"></i><span>返回登录</span>
        </div>
        <el-tabs v-model="modifiesPasswordActiveName">
          <el-tab-pane label="修改密码" name="modifiedPassword">
            <el-form ref="modifyPwdForm" label-position="top" :rules="modifyPwdFormRules" :model="modifyPwdForm" size="default">
              <el-form-item class="login-form-item" prop="cellphone">
                <el-input
                  placeholder="请输入您的手机号码"
                  prefix-icon="el-icon-phone-outline"
                  v-model="modifyPwdForm.cellphone">
                </el-input>
              </el-form-item>
              <el-form-item class="login-form-item" prop="verifyCode">
                <el-row :gutter="14">
                  <el-col :span="14">
                    <el-input
                      placeholder="请输入验证码"
                      prefix-icon="el-icon-chat-dot-square"
                      v-model="modifyPwdForm.verifyCode">
                    </el-input>
                  </el-col>
                  <el-col :span="10">
                    <div class="send-verify">
                      <el-button plain @click="sendModifyPwdVerify()" :disabled="this.modifyPwdVerifySending">{{
                        this.modifyPwdVerifySending ? `${this.modifyPwdVerifyCountDown}s` : '发送验证码'
                      }}</el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item class="login-form-item" prop="newPassword">
                <el-input
                  prefix-icon="el-icon-lock"
                  v-model="modifyPwdForm.newPassword"
                  placeholder="请输入新密码"
                  autocomplete="off"
                  maxlength="16"
                  show-password
                ></el-input>
              </el-form-item>
              <el-form-item class="login-form-item" prop="affirmPassword">
                <el-input
                  prefix-icon="el-icon-lock"
                  v-model="modifyPwdForm.affirmPassword"
                  placeholder="请确认新密码"
                  autocomplete="off"
                  maxlength="16"
                  show-password
                ></el-input>
              </el-form-item>
            </el-form>
            <div class="login-form-item">
              <el-button size="default" @click="modifyPwdSubmit" type="primary" class="button-login" :loading="loading">
                提交
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-show="accountRegisterTabShow">
        <div class="back-login" @click="switchModel('accountLogin')">
          <i class="el-icon-caret-left"></i><span>返回登录</span>
        </div>
        <el-tabs v-model="registerActiveName">
          <el-tab-pane label="注册账号" name="accountRegister">
            <el-form ref="registerForm" label-position="top" :rules="registerFormRules" :model="registerForm" size="default">
              <el-form-item class="login-form-item" prop="name">
                <el-input
                  prefix-icon="el-icon-s-custom"
                  v-model="registerForm.name"
                  placeholder="请输入姓名"
                  autocomplete="off"
                  maxlength="32">
                </el-input>
              </el-form-item>
              <el-form-item class="login-form-item" prop="username">
                <el-input
                  prefix-icon="el-icon-user"
                  v-model="registerForm.username"
                  placeholder="请输入账号"
                  autocomplete="off"
                  maxlength="16">
                </el-input>
              </el-form-item>
              <el-form-item class="login-form-item" prop="password">
                <el-input
                  prefix-icon="el-icon-lock"
                  v-model="registerForm.password"
                  placeholder="请输入密码"
                  autocomplete="off"
                  maxlength="16"
                  show-password
                ></el-input>
              </el-form-item>
              <el-form-item class="login-form-item" prop="mobile">
                <el-input
                  prefix-icon="el-icon-phone-outline"
                  v-model="registerForm.mobile"
                  placeholder="请输入手机号码"
                  autocomplete="off"
                  maxlength="16"
                ></el-input>
              </el-form-item>
            </el-form>
            <div class="login-form-item">
              <el-button size="default" @click="accountRegisterSubmit" type="primary" :loading="loading">
                提交
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <helpModel :visible.sync="helpVisible"></helpModel>
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import helpModel from './toolsbar/help.vue';
import ddSlider from '@/components/dd-slider'

export default {
  name: 'login-page',
  components: {
    helpModel,
    ddSlider
  },
  data() {
    const validateSlide = (rule, value, callback) => {
      this.verify === false ? callback(new Error()) : callback();
    };
    const checkPwdConsistent = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请确认新密码'));
      }
      if (value !== this.modifyPwdForm.newPassword) {
        return callback(new Error('请确保密码一致'));
      }
      callback();
    };
    return {
      helpVisible: false,
      loginActiveName: 'accountLogin',
      modifiesPasswordActiveName: 'modifiedPassword',
      registerActiveName: 'accountRegister',
      verifyWidth: 330,
      verifyHeight: 59,

      accountLoginTabShow: true,
      modifyPwdTabShow: false,
      accountRegisterTabShow: false,

      verify: false, // 滑动验证标识
      formType: true, // 表单类型
      formLoginDisplay: 'display: flex;',
      formModifyPwdDisplay: 'display: none;',
      cellphoneLoginVerifySending: false, // 手机号登录验证码发送状态
      modifyPwdVerifySending: false, // 修改密码验证码发送状态
      cellphoneLoginVerifyCountDown: 60, // 手机号登录发送倒计时
      modifyPwdVerifyCountDown: 60, // 修改密码发送倒计时
      loading: false, // 按钮加载状态
      // 用户名密码登录表单
      formLogin: {
        username: '',
        password: '',
        code: '',
      },
      // 手机登录表单
      cellphoneLoginForm: {
        cellphone: '',
        verifyCode: '',
      },
      // 修改密码表单
      modifyPwdForm: {
        cellphone: '',
        verifyCode: '',
        newPassword: '',
        affirmPassword: '',
      },

      // 注册账号表单
      registerForm: {
        name: '',
        username: '',
        password: '',
        mobile: ''
      },

      // 账号登录表单校验
      accountLoginFormRules: {
        username: [
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
        ],
        verify: [
          {
            required: true,
            message: '请滑动验证',
            validator: validateSlide,
          },
        ],
      },

      // 手机号登录表单校验
      cellphoneLoginFormRules: {
        cellphone: this.$Validate.mobile(true, '请输入手机号码'),
        verifyCode: [
          {
            required: true,
            message: '请输入手机验证码',
            trigger: 'blur',
          },
        ],
      },

      // 修改密码表单验证
      modifyPwdFormRules: {
        cellphone: this.$Validate.mobile(true, '请输入手机号码'),
        verifyCode: [
          {
            required: true,
            message: '请输入手机验证码',
            trigger: 'blur',
          },
        ],
        newPassword: this.$Validate.password(true, '请输入新密码'),
        affirmPassword: [
          {
            required: true,
            validator: checkPwdConsistent,
            trigger: 'blur',
          },
        ],
      },

      // 注册表单验证
      registerFormRules: {
        mobile: this.$Validate.mobile(true, '请输入手机号码'),
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
          },
        ],
        username: [
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
        ]
      },
    };
  },
  beforeCreate() {
    this.validateSlide;
  },
  mounted() {
    this.windowResize();
  },
  beforeDestroy() {},
  methods: {
    ...mapActions('ddAdmin/account', ['accountLogin']),
    windowResize() {
      window.addEventListener('resize', () => {
        //this.verifyWidth = (window.innerWidth / 100) * 21;
        //this.verifyHeight = (window.innerHeight / 100) * 6;
      });
    },

    // 头部工具栏打开项
    toolsBarModelOpen(toolName) {
      switch (toolName) {
        case 'help':
          this.helpVisible = true;
          break;
        default:
          break;
      }
    },

    // 滑动验证成功的回调
    successVerify: function () {
      let param = {
        text: true
      };
      this.$api.oauth
        .getCheckCode(param)
        .then((res) => {
          if (res.error === 0) {
            this.verify = true;
            this.formLogin.code = res.value;
          } else {
            this.sliderReset();
          }
        })
        .catch((err) => {
          this.sliderReset();
        });
    },

    // 滑动块重置
    sliderReset: function () {
      this.verify = false;
      this.$refs.verify.reset();
    },

    // 监听type
    typeChange: function () {
      this.formType = !this.formType;
      this.sendBtnStatusChange();
    },

    // 修改密码发送验证码
    sendModifyPwdVerify: function () {
      this.$refs.modifyPwdForm.validateField('cellphone', (validMsg) => {
        if (!validMsg) {
          this.$api.user.getVerifyCode({ cellphone: this.modifyPwdForm.cellphone }).then((res) => {
            this.modifyPwdVerifySending = !this.modifyPwdVerifySending;
            if (this.modifyPwdVerifySending) {
              this.$message.success('发送成功');
              let cl = setInterval(() => {
                this.modifyPwdVerifyCountDown--;
                if (this.modifyPwdVerifyCountDown < 0) {
                  this.modifyPwdVerifySending = false;
                  clearInterval(cl);
                }
              }, 1000);
            }
          });
        } else {
          return false;
        }
      });
    },

    // 手机号登录发送验证码
    sendCellphoneLoginVerify: function () {
      this.$refs.cellphoneLoginForm.validateField('cellphone', (validMsg) => {
        if (!validMsg) {
          this.$api.oauth.getCode({ cellphone: this.cellphoneLoginForm.cellphone}).then((res) => {
            this.cellphoneLoginVerifySending = !this.cellphoneLoginVerifySending;
            if (this.cellphoneLoginVerifySending) {
              this.$message.success('发送成功');
              let cl = setInterval(() => {
                this.cellphoneLoginVerifyCountDown--;
                if (this.cellphoneLoginVerifyCountDown < 0) {
                  this.cellphoneLoginVerifySending = false;
                  clearInterval(cl);
                }
              }, 1000);
            }
          });
        } else {
          return false;
        }
      });
    },

    // 账号密码登录提交
    loginSubmit: function () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.accountLogin({
            username: this.formLogin.username,
            password: this.formLogin.password,
            code: this.formLogin.code,
            loginType: 1,
          })
          .then(() => {
            this.loading = false;
            // 重定向对象不存在则返回顶层路径
            this.$router.replace(this.$route.query.redirect || '/');
            // 加载资源
            this.$store.dispatch('ddAdmin/account/loadResource');
          })
          .catch((err) => {
            // 异常捕获
            this.loading = false;
            this.sliderReset();
          });
        }
      });
    },

    // 手机号登录提交
    cellphoneLoginSubmit: function () {
      this.$refs.cellphoneLoginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.accountLogin({
            username: this.cellphoneLoginForm.cellphone,
            code: this.cellphoneLoginForm.verifyCode,
            loginType: 2,
          })
            .then(() => {
              this.loading = false;
              // 重定向对象不存在则返回顶层路径
              this.$router.replace(this.$route.query.redirect || '/');
              // 加载资源
              this.$store.dispatch('ddAdmin/account/loadResource');
            })
            .catch((err) => {
              // 异常捕获
              this.loading = false;
              this.sliderReset();
            });
        }
      });
    },

    // 切换修改密码窗口
    switchModifyPasswordTab() {
      this.accountLoginTabShow = !this.accountLoginTabShow;
    },

    // 切换窗口
    switchModel(modelName) {
      this.modifyPwdTabShow = false;
      this.accountLoginTabShow = false;
      this.accountRegisterTabShow = false;
      switch (modelName) {
        case 'accountLogin':
          this.accountLoginTabShow = true;
          break;
        case 'accountRegister':
          this.accountRegisterTabShow = true;
          break;
        case 'modifiedPassword':
          this.modifyPwdTabShow = true;
          break;

        default:
          break;
      }
    },

    // 修改密码提交
    modifyPwdSubmit: function () {
      this.$refs.modifyPwdForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$api.user
            .updatePwdByVerifyCode(this.modifyPwdForm)
            .then(() => {
              this.loading = false;
              this.modifyPwdVerifySending = false;
              this.$message.success('密码修改成功');
            })
            .catch((err) => {
              // 异常捕获
              this.loading = false;
            });
        }
      });
    },

    // 账号注册
    accountRegisterSubmit() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$api.oauth
            .register(this.registerForm)
            .then((res) => {
              if (res.error === 0) {
                this.$message.success('账号注册成功');
                this.$refs.registerForm.resetFields();
              } else {
                this.$message.error('账号注册失败,' + res.description);
              }
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss">
.page-login {
  $backgroundColor: #f0f2f5;
  background-image: url('./image/login-bg.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-color: $backgroundColor;
  height: 100%;
  position: relative;

  .page-login-header {
    height: 115px;
    width: 100%;
    .title {
      padding-top: 2.9vh;
      padding-left: 2.2vw;
      line-height: 35px;
      .logo {
        float: left;
        text-align: left;
        width: 35px;
        height: 35px;
        background-repeat: no-repeat;
        background-size: 100% 100%;
        background-image: url('./image/logo.png');
      }
      .app-name {
        float: left;
        font-size: 25px;
        text-align: left;
        font-weight: Bold;
        color: #173d7b;
        padding-left: 12px;
      }
    }

    .toolbar {
      float: right;
      padding-right: 36px;
      line-height: 2.3vw;
      .help {
        cursor: pointer;
        width: 30px;
        height: 30px;
        background-repeat: no-repeat;
        background-size: 100% 100%;
        background-image: url('./image/help.png');
      }
      .help:hover {
        background-color: #a5c7e7;
        border-radius: 6px;
      }
    }
  }

  .login-layer {
    margin-right: 7vw;
    margin-top: 5vh;
    float: right;
    width: 335px;
    position: relative;
    border-radius: 10px 10px 10px 10px;
    background: rgba(255, 255, 255, 1);
    padding: 5.4vh 5vw;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    .el-tabs {
      .el-tabs__item {
        font-size: 3vh;
        color: #475669;
      }
      .el-tabs__nav {
        height: 6vh;
      }
      .el-tabs__item.is-active {
        color: #2b5fed;
        font-weight: Bold;
      }
      .el-tabs__active-bar {
        background-color: #475669;
        height: 4px;
        width: 4vw !important;
        margin: 0 1vw;
      }
      .el-tabs__nav-wrap::after {
        width: 0%;
      }
    }

    .el-input {
      font-size: 1.6vw;
      .el-input__icon {
        width: 2.4vw;
        line-height: 6vh;
        color: #939393;
      }
      .el-input__inner {
        height: 6vh;
        border-radius: 5px;
        border: 3px solid #dcdcdc;
        padding-left: 46px;
        font-size: 18px;
        // 不跟随系统主题颜色
        color: #666260 !important;
        background-color: #ffffff !important;
      }
    }

    .login-form-item {
      width: 100%;
      padding: 1.6vh 0px;
      .el-form-item__error {
        font-size: 2vh;
      }
    }

    .forget {
      color: #2b5fed;
      font-size: 1.1vw;
      height: 1.3vw;
      width: 100%;
      cursor: pointer;
      span {
        float: right;
      }
    }
    .no-account {
      text-align: center;
      font-size: 2vh;
      .register {
        color: #2b5fed;
        font-weight: bold;
        cursor: pointer;
      }
    }
    .el-tabs__content {
      .el-button {
        width: 100%;
        height: 6vh;
        font-size: 2vh;
        background: #2b5fed !important;
      }
    }

    .send-verify {
      .el-button {
        background: #fff !important;
        border: 3px solid #dcdcdc;
      }
    }

    .slide {
      .verify-tips {
        font-size: 18px;
      }
      .verify-success-tips {
        font-size: 18px;
      }
      .verify-box {
        border-radius: 10px !important;
      }
      .verify-bar {
        left: -1px;
        top: 0px;
        width: 50px;
        .icon {
          width: 44px !important;
          height: 46px !important;
          line-height: 52px;
          border-radius: 10px !important;
          background-image: url('./image/verify.png') !important;
          background-size: 100% 100% !important;
          color: #fff !important;
          text-align: center;
          color: hsla(0, 0%, 75%, 1);
        }
      }
    }

    .back-login {
      float: left;
      left: 1vw;
      top: 2vh;
      position: absolute;
      text-align: center;
      color: #2b5fed;
      cursor: pointer;
    }
  }
}
</style>
